﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.Xml.Linq;
using ProtoType.DataStorage;
using System.Collections.ObjectModel;
using ProtoType.ProtoTypeService;

namespace ProtoType
{
    public partial class DetailLayOutControls : PhoneApplicationPage
    {
        ProtoTypeServiceClient client;
        AppSettings apps = new AppSettings();
        DataStructureStore dss = new DataStructureStore();
        ObservableCollection<XElement> formslist;
        string selectedfid = "";
        string selecteddetaillayouttype = "Simple";
        string bindingid = "";

        public DetailLayOutControls()
        {
            InitializeComponent();
            client = new ProtoTypeServiceClient();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.TryGetValue("selectedfid", out selectedfid))
            {
                if (apps.IsolatedStorageSavingSetting)
                {
                    selecteddetaillayouttype = dss.GetSelectedDetailLayOutType(selectedfid);
                    RenderControls(selecteddetaillayouttype);
                    if (NavigationContext.QueryString.TryGetValue("bindingid", out bindingid))
                    {
                        formslist = dss.LoadFormList();
                        LoadformList();
                    }
                }
                if (apps.WebServiceSavingSetting)
                {
                    client.GetSelectedDetailLayOutTypeAsync(selectedfid);
                    client.GetSelectedDetailLayOutTypeCompleted += new EventHandler<GetSelectedDetailLayOutTypeCompletedEventArgs>(client_GetSelectedDetailLayOutTypeCompleted);
                }
            }
        }

        void client_GetSelectedDetailLayOutTypeCompleted(object sender, GetSelectedDetailLayOutTypeCompletedEventArgs e)
        {
            selecteddetaillayouttype = e.Result.ToString();
            RenderControls(selecteddetaillayouttype);
            if (NavigationContext.QueryString.TryGetValue("bindingid", out bindingid))
            {
                BindDatafromService();
            }
        }

        private void BindDatafromService()
        {
            client.LoadformListAsync();
            client.LoadformListCompleted += new EventHandler<LoadformListCompletedEventArgs>(client_LoadformListCompleted);
        }

        void client_LoadformListCompleted(object sender, LoadformListCompletedEventArgs e)
        {
            formslist = e.Result.ToObservableCollection();
            LoadformList();
        }

        void LoadformList()
        {
            Uri uri = new Uri("SampleData/DetailLayout.xml", UriKind.Relative);
            XDocument layoutdoc = XDocument.Load(uri.ToString());
            var layoutdef = from layout in layoutdoc.Descendants("layout") where layout.Attribute("Name").Value == selecteddetaillayouttype select layout;
            List<TextBox> textboxes = new List<TextBox>();
            textboxes = StaticClass.GetTextBoxes(ContentGrid, textboxes);
            foreach (XElement t in layoutdef.Descendants("control"))
            {
                foreach (TextBox tb in textboxes)
                {
                    if (tb.Name == t.Value.Replace(" ", ""))
                    {
                        IEnumerable<XElement> elements = formslist.Elements("detaillayout");
                        foreach (XElement ea in elements)
                        {
                            if (ea.Element(tb.Name) != null)
                            {
                                tb.Text = ea.Element(tb.Name).Element("name").Value;
                                tb.Tag = ea.Element(tb.Name).Element("bid").Value; ;
                                break;
                            }
                        }
                    }
                }
            }
        }

        private void RenderControls(string selecteddetaillayouttype)
        {
            Uri uri = new Uri("SampleData/DetailLayout.xml", UriKind.Relative);
            XDocument Xdoc = XDocument.Load(uri.ToString());

            var template = from temp in Xdoc.Descendants("layout") where temp.Attribute("Name").Value == selecteddetaillayouttype select temp;

            DataTemplates dt = new DataTemplates();
            spcontrol.Children.Clear();

            foreach (XElement t in template.Descendants("control"))
            {

                StackPanel childsp = new StackPanel();

                Button btn = new Button();
                btn.Width = 50;
                btn.Content = "->";
                btn.Tag = t.Value.Replace(" ", "");
                btn.Click += new RoutedEventHandler(btn_Click);

                TextBox tbox = dt.CreateATextBox(t.Value.Replace(" ", ""));
                tbox.IsEnabled = false;
                btn.Width = 100;
                childsp.Children.Add(dt.CreateATextBlock(t.Value));
                childsp.Children.Add(btn);
                childsp.Children.Add(tbox);
                spcontrol.Children.Add(childsp);
            }
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            string s = btn.Tag.ToString();
            NavigationService.Navigate(new Uri("/DetailFieldsList.xaml?tag=" + s + "&selectedfid=" + selectedfid, UriKind.Relative));
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/FormsList.xaml", UriKind.Relative));
        }
    }
}